package com.googlecode.pacswitch.actions;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.TimeUnit;

import javax.xml.bind.annotation.XmlType;

import com.googlecode.pacswitch.Action;
import com.googlecode.pacswitch.CloseOnCompleteHandler;
import com.googlecode.pacswitch.Log;
import com.googlecode.pacswitch.ObjectFactory;
import com.googlecode.pacswitch.PString;
import com.googlecode.pacswitch.PacSwitch;

/**
 * @author Andrey Pavlenko
 */
@XmlType(name = "plain", namespace = ObjectFactory.ANS)
public class Plain extends PString implements Action {

    public Plain(final String text) {
        super(text);
    }

    @Override
    public void perform(final PacSwitch ps,
            final AsynchronousSocketChannel clientSocket) {
        final Log log = ps.getConfig().getLog();
        final String response = resolve(ps, clientSocket);
        final ByteBuffer b = ByteBuffer.wrap(response.getBytes());
        final CloseOnCompleteHandler handler = new CloseOnCompleteHandler(ps,
                clientSocket);

        if (log.isDebugEnabled()) {
            log.debug("Sending text response:\r\n" + response);
        }

        clientSocket.write(b, 30, TimeUnit.SECONDS, null, handler);
    }
}
